package tree;


public class SolutionFour {
    int ans = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        dfs(root);
        return ans;
    }

    public int dfs(TreeNode root){
        if(root == null){
            return 0;
        }
        int left = Math.max(root.val,dfs(root.left) + root.val);
        int right = Math.max(root.val,dfs(root.right) + root.val);
        ans = Math.max(ans,left+right-root.val);
        return Math.max(left,right);
    }

    public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }
}
